#!/usr/bin/bash
#
# Get MAC and IPv4 address of VM
#

FILE=$(readlink -f "${BASH_SOURCE[0]}")
CDIR=$(dirname "$FILE")
NAME=$(basename "$FILE")
TMPDIR=${TMPDIR:-"/tmp"}

function get_mac_address
{
    typeset dom_name=${1?"*** Domain name"}
    typeset mac_info=$(sudo virsh dumpxml $dom_name | egrep 'mac.*address=')
    typeset s=$(echo $mac_info | awk -F'=' '{print $NF}')
    typeset mac_address=$(echo ${s%/*} | xargs echo)
    echo $mac_address
}

function get_ipv4_address
{
    typeset mac_address=${1?"*** MAC address"}
    typeset arp_info=$(arp -a | grep -E "$mac_address")
    typeset ipv4_address=$(echo ${arp_info%)*} | awk -F'(' '{print $NF}')
    echo $ipv4_address
}

dom_name=${1?"*** VM name, e.g. hnli-AnolisOS23.1-foo"}
mac=$(get_mac_address $dom_name)
if [[ -z $mac ]]; then
    echo "Oops, failed to get mac address of VM $dom_name" >&2
    exit 1
fi

ipv4=$(get_ipv4_address $mac)
if [[ -z $ipv4 ]]; then
    echo "Oops, failed to get IPv4 address of VM $dom_name" >&2
    exit 1
fi

echo
echo "MAC  ADDRESS: $mac"
echo "IPv4 ADDRESS: $ipv4"
echo
echo "To ssh access $dom_name, please try:"
echo ">>>"
echo ">>> ssh anuser@$ipv4 # password: anolisos"
echo ">>>"
echo ">>> # OR"
echo ">>>"
echo ">>> ssh   root@$ipv4 # password: R******9"
echo ">>>"
echo
